﻿namespace Gonte.Workflow.Tasks
{
    /// <summary>
    /// Retrieves an object from the task context by its instance name
    /// </summary>
    public class GetInstance
        : ITask
    {
        #region Constructors

        public GetInstance()
        {
        }

        public GetInstance(string instance)
        {
            _instance = instance;
        } 

        #endregion

        #region ITask Members

        public virtual TaskResult Execute(TaskContext context)
        {
            TaskResult result = new TaskResult();
            result.Value = FetchInstance(context);

            return result;
        }

        #endregion

        #region Properties

        /// <summary>
        /// The name of the instance of the object to access
        /// </summary>
        public string Instance
        {
            get { return _instance; }
            set { _instance = value; }
        } 

        #endregion

        #region Helpers

        private object FetchInstance(TaskContext context)
        {
            ExceptionThrower.ThrowWhenNullOrEmpty("Instance", _instance);

            object data = context.GetLocal(_instance);

            if (null == data)
            {
                ExceptionThrower.ThrowWhenNot(context.Globals.ContainsKey(_instance),
                    string.Format("Unable to find instance of name: '{0}'", _instance));

                data = context.Globals[_instance];
            }

            return data;
        } 

        #endregion 

        #region Fields

        private string _instance;

        #endregion
    }
}
